#!/usr/bin/env python

import logging    
                        
#: Should return anything to allow access to resource
ALLOWED_BODY = '''\r\n'''                  

#: Could be customzed to fit your needs, some examples are '''Position 403: You are more then welcome to come here <img src='http://www.lemonparty.org/lemonparty.jpg'>'''
FORBIDDEN_BODY = '''Status: 403 Forbidden\r\n\r\n'''
   
    

def authorizer(environ, start_response):       
    """ WSGI application which decides if request has permission to access resource according to FastCGI_authorizer_
                                                                                                                                       
    How it works
    ============
    FastCGI could be used as remote authorizer, which is quite handfull for access to static resources. 
    Server before accesing url asks authorizer application for authentication. 
    Authorizer application is just HTTP (FastCGI) aplication.

    Motivation
    -----------                              
    Flexibly, easyliy and securily allow access to resources.
    
    Authorizer could run on server itself (using different privileges), providing autorization information for different resources.
    
    This costs CPU, but on file-serving hosts this is no crucial. 
    
    Returns                                                                                              
    -------    
    200 - *allowed* (response body is ignored)
    403 - *forbidden* - customize forbidden response by settings ``FORBIDDEN_BODY`` to desired message 
                         
    Example in C according do Lighttpd_FastCGIAuthorizer_
    =====================================================    
    .. sourcecode: c

        #include <fcgi_stdio.h>
        #include <stdlib.h>
        #include <unistd.h>
        int main () {
          char* p;

          while (FCGI_Accept() >= 0) {
            /* wait for fastcgi authorizer request */

            printf("Content-type: text/html\r\n");

            if ((p = getenv("QUERY_STRING")) == NULL) ||
                 <QUERY_STRING is unauthorized>)
                 printf("Status: 403 Forbidden\r\n\r\n");

            else printf("\r\n");
              /* default Status is 200 - allow access */
          }

          return 0;
        }
                           
    Pros
    ====
    * Flexibility
    * Flexibility
    * Security (as autorizer is able to run in chrooted environment)
        
    Cons
    ====
    * Authentication included in server or as mod could be many times faster. 
    
    Usage
    =====
    Should be used in Lighttpd_FastCGIAuthorizer_

    .. _FastCGI_authorizer:  http://www.fastcgi.com/devkit/doc/fcgi-spec.html#S6.3           
    .. _Lighttpd_FastCGIAuthorizer: http://trac.lighttpd.net/trac/wiki/Docs%3AModFastCGI#skeleton-for-remote-authorizer
    """           
    headers = [('Content-type', 'text/html')]     # TODO: Spec?  
    
    allowed = False                                # iptables -P INPUT DROP     
    # print "WITKA"   
    # TODO: is_allowed method should be used here                                   
    if allowed:
        status = '200 OK'      
        body = ALLOWED_BODY
    else:
        status = '403 Forbidden'    
        body = FORBIDDEN_BODY
    
    start_response(status, headers)
    yield body


def fastcgi_server(port = 8000):
    # from flup.server.fcgi_fork import WSGIServer
    # fcgid = WSGIServer(authorizer) 
    # fcgid.run() 
    #                    
    from flup.server.fcgi import WSGIServer  
    # print help(WSGIServer)
    WSGIServer(authorizer).run()    
    
def http_server(port = 8000):    
    from wsgiref.simple_server import make_server    
    httpd = make_server('', port, authorizer)
    httpd.serve_forever()

def main():      
    fastcgi_server()                                
    # http_server()         
    
if __name__ == '__main__':
    main()
